﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CDSBDemandControl.Presenter;
using CDSBDemandControl.Model;
using System.Drawing;
using System.Data;

namespace CDSBDemandControl.View.Web.PaginasInternas
{
    public partial class SolicitacoesSites : System.Web.UI.Page, IDiscriminatorDemand
    {
        private Presenter.DiscriminatorDemand Presenter;
        private const string ASCENDING = " ASC";
        private const string DESCENDING = " DESC";
        private int i = 0;

        private SortDirection GridViewSortDirectionSolicitacoes
        {
            get
            {
                if (ViewState["sortDirectionSolicitacoes"] == null)
                    ViewState["sortDirectionSolicitacoes"] = SortDirection.Ascending;

                return (SortDirection)ViewState["sortDirectionSolicitacoes"];
            }
            set { ViewState["sortDirectionSolicitacoes"] = value; }
        }

        private SortDirection GridViewSortDirectionAndamento
        {
            get
            {
                if (ViewState["sortDirectionAndamento"] == null)
                    ViewState["sortDirectionAndamento"] = SortDirection.Ascending;

                return (SortDirection)ViewState["sortDirectionAndamento"];
            }
            set { ViewState["sortDirectionAndamento"] = value; }
        }

        private SortDirection GridViewSortDirectionIntegrados
        {
            get
            {
                if (ViewState["sortDirectionIntegrados"] == null)
                    ViewState["sortDirectionIntegrados"] = SortDirection.Ascending;

                return (SortDirection)ViewState["sortDirectionIntegrados"];
            }
            set { ViewState["sortDirectionIntegrados"] = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Cache.SetExpires(DateTime.Now.Subtract(new TimeSpan(24, 0, 0)));
            Response.Cache.SetCacheability(HttpCacheability.NoCache);

            if (!this.IsPostBack || this.Session["Presenter"] == null)
            {
                this.Presenter = new DiscriminatorDemand(this);

                this.Session["Presenter"] = this.Presenter;

                if (!this.IsPostBack) this.ListarSolicitacoes();
            }
            else
            {
                this.Presenter = (Presenter.DiscriminatorDemand)this.Session["Presenter"];
                this.Presenter.ResetView(this);
            }
        }

        private void ListarSolicitacoes()
        {
            this.Presenter.ListarSolicitacoes();
        }

        void IDiscriminatorDemand.ExibirSolicitacoesSites(List<CDSBDemandControl.Model.DemandModel> demandModels)
        {
            //configurando datas
            foreach (DemandModel model in demandModels)
            {
                this.configurarValorDataHoras(model);
            }

            Session["scenarios"] = demandModels;

            List<DemandModel> solicitacoes = (from dem in demandModels
                                              where dem.State == "Em Avaliação de Demanda" ||
                                              (
                                              dem.AssignedTo == "Rodrigo Sanches Pena" && dem.State == "Em Especificação (Funcional)"
                                              )
                                              select dem).ToList<DemandModel>();

            List<DemandModel> andamento = (from dem in demandModels
                                           where (dem.State != "Encerrado" && dem.State != "Em Avaliação de Demanda")
                                           &&
                                           !(dem.AssignedTo == "Rodrigo Sanches Pena" && dem.State == "Em Especificação (Funcional)")
                                              select dem).ToList<DemandModel>();

            List<DemandModel> entregue = (from dem in demandModels
                                           where dem.State == "Encerrado"
                                           select dem).ToList<DemandModel>();

            Session["solicitacoes"] = solicitacoes;
            this.GridSolicitacoesSites.DataSource = (List<DemandModel>)Session["solicitacoes"];
            this.GridSolicitacoesSites.DataBind();

            Session["andamento"] = andamento;
            this.GridProjetosEmAndamento.DataSource = (List<DemandModel>)Session["andamento"];
            this.GridProjetosEmAndamento.DataBind();

            Session["entregue"] = entregue;
            this.GridProjetosIntegrados.DataSource = (List<DemandModel>)Session["entregue"];
            this.GridProjetosIntegrados.DataBind();

            (this.Master.FindControl("LblUltimoUpdate") as Label).Text = "Última atualização em: " + this.Presenter.SolicitacoesSitesLastUpdate.ToShortDateString() + " as " + this.Presenter.SolicitacoesSitesLastUpdate.ToShortTimeString();

            this.ExibirObservacao("Acompanhamento de Demandas TeamProject Site");
        }

        private void ExibirObservacao(string obs)
        {
            this.LblObsOrdenacao.Text = obs;
            this.LblObsOrdenacao.Visible = this.LblObsOrdenacao.Text.Length > 0 ? true : false;
        }

        protected void Grid_DataBinding(object sender, EventArgs e)
        {
            ((GridView)sender).Visible = true;
        }

        protected void Grid_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DemandModel current = ((CDSBDemandControl.Model.DemandModel)(e.Row.DataItem));

                LinkButton lnkPopUp = (LinkButton)e.Row.FindControl("lnkPopUp");
                if (lnkPopUp != null)
                {
                    lnkPopUp.CommandArgument = current.ID;
                }

                e.Row.Cells[3].Text = current.Start == DateTime.MinValue ? "N/A" : current.Start.Value.ToString("dd/MM/yyyy");
                e.Row.Cells[4].Text = current.Conclude == DateTime.MinValue ? "N/A" : current.Conclude.Value.ToString("dd/MM/yyyy");

                if (current.Conclude.Value.Date != DateTime.MinValue && DateTime.Now.Date > current.Conclude.Value.Date && current.State != "Encerrado")
                    e.Row.Cells[4].ForeColor = Color.Red;
            }

        }

        private void configurarValorDataHoras(DemandModel current)
        {
            Decimal sum = 0;
            sum += current.GeneralRealizedTime;
            sum += current.MEDRTFRealizedTime;
            sum += current.XAMLRealizedTime;
            sum += current.ArchitectureRealizedTime;
            sum += current.DevelopmentRealizedTime;
            sum += current.TestsRealizedTime;

            current.UsedHours = sum;

            DateTime dtStart = DateTime.MinValue;
            DateTime dtConclude = DateTime.MinValue;

            string state = current.State;

            switch (state)
            {
                case "XXX":
                    {
                        dtStart = DateTime.Now;
                        dtConclude = DateTime.Now;
                    }
                break;
                case "Em Avaliação de Demanda":
                    {
                        dtStart = current.AssessingDemandPlannedStartDate;
                        dtConclude = current.AssessingDemandPlannedEndDate;
                    }
                    break;
                case "Em Especificação (Funcional)":
                    {
                        dtStart = current.GeneralPlannedStartDate;
                        dtConclude = current.GeneralPlannedEndDate;
                    }
                    break;
                case "Em Análise (Ger. Produto)":
                    {
                        dtStart = current.GeneralRealizedStartDate;
                        dtConclude = current.GeneralRealizedEndDate;
                    }
                    break;
                case "Em Especificação (Arquitetura)":
                    {
                        dtStart = current.ArchitecturePlannedStartDate;
                        dtConclude = current.ArchitecturePlannedEndDate;
                    }
                    break;
                case "Aprovado para Desenvolvimento":
                    {
                        dtStart = current.DevelopmentRealizedStartDate;
                        dtConclude = current.DevelopmentRealizedEndDate;
                    }
                    break;
                case "Em Desenvolvimento":
                    {
                        dtStart = current.DevelopmentPlannedStartDate;
                        dtConclude = current.DevelopmentPlannedEndDate;
                    }
                    break;
                case "Aprovado para Testes":
                    {
                        dtStart = current.TestsPlannedStartDate;
                        dtConclude = current.TestsPlannedEndDate;
                    }
                    break;
                case "Em Testes":
                    {
                        dtStart = current.TestsPlannedStartDate;
                        dtConclude = current.TestsPlannedEndDate;
                    }
                    break;
                case "Liberado para Integração":
                    {
                        dtStart = current.AcceptedPlannedStartDate;
                        dtConclude = current.AcceptedPlannedEndDate;
                    }
                    break;
                case "Integrado em Certificação":
                    {
                        dtStart = current.AcceptedPlannedStartDate;
                        dtConclude = current.AcceptedPlannedEndDate;
                    }
                    break;
                case "Validar Certificação":
                    {
                        dtStart = current.AcceptedPlannedStartDate;
                        dtConclude = current.AcceptedPlannedEndDate;
                    }
                    break;
                case "Aprovado em Certificação":
                    {
                        dtStart = current.AcceptedPlannedStartDate;
                        dtConclude = current.AcceptedPlannedEndDate;
                    }
                    break;
                case "Validação Usuario":
                    {
                        dtStart = current.AcceptedPlannedStartDate;
                        dtConclude = current.AcceptedPlannedEndDate;
                    }
                    break;
                case "Validação OK":
                    {
                        dtStart = current.AcceptedPlannedStartDate;
                        dtConclude = current.AcceptedPlannedEndDate;
                    }
                    break;
                case "Validação NOK":
                    {
                        dtStart = current.AcceptedPlannedStartDate;
                        dtConclude = current.AcceptedPlannedEndDate;
                    }
                    break;
                case "Integrado em Produção":
                    {
                        dtStart = current.AcceptedRealizedStartDate;
                        dtConclude = current.AcceptedRealizedEndDate;
                    }
                    break;
                case "Validar Produção":
                    {
                        dtStart = current.AcceptedRealizedStartDate;
                        dtConclude = current.AcceptedRealizedEndDate;
                    }
                    break;
                case "Encerrado":
                    {
                        dtStart = current.AcceptedRealizedStartDate;
                        dtConclude = current.AcceptedRealizedEndDate;
                    }
                    break;
                case "Cancelado":
                    {
                        dtStart = current.AssessingDemandPlannedStartDate;
                        dtConclude = current.AssessingDemandPlannedEndDate;
                    }
                    break;
            }
            current.Start = dtStart;
            current.Conclude = dtConclude;
        }

        public string formatTitle(object title, object description)
        {
            /*i++;
            string id = i + title.ToString().ToLower().Trim().Replace(" ", "").Replace("-", "").Replace("á", "").Replace("ç", "").Replace("(", "").Replace(")", "").Replace("ã", "").Replace("õ", "");
            string content = description == null ? null : description.ToString();

            string link = "<span onclick=\"javascript:{ var aux =  document.getElementById('" + id + "'); var auxLink =  document.getElementById('span" + id + "'); if(aux.style.display == 'none') {aux.style.display = 'block'; auxLink.innerHTML = '<b>&nbsp;(-)</b>';} else {aux.style.display = 'none'; auxLink.innerHTML = '<b>&nbsp;(+)</b>';}}\"><span id='" + "span" + id + "' style='cursor:hand; color:red;'><b> (+)</b></span><b>" + title + "</b></span>";

            string div = link + @"<div id='" + id + "' style='display:none; position:relative;'><i>" + content + "</i></div>";

            if (string.IsNullOrEmpty(content))
                return "<b>" + title + "</b>";
            else
                return div;*/
            return title.ToString();
        }

        protected void lnkPopUp_Click(object sender, EventArgs e)
        {
            Session["scenarioID"] = ((LinkButton)sender).CommandArgument;
            ClientScript.RegisterStartupScript(this.GetType(), "OpenWindowStartupScript", "javascript:window.open('ScenarioDetail.aspx','ScenarioDetail','width=1100,height=600,scrollbars=yes');", true);

            GridSolicitacoesSites.DataSource = (List<DemandModel>)Session["solicitacoes"];
            GridSolicitacoesSites.DataBind();

            GridProjetosEmAndamento.DataSource = (List<DemandModel>)Session["andamento"];
            GridProjetosEmAndamento.DataBind();

            GridProjetosIntegrados.DataSource = (List<DemandModel>)Session["entregue"];
            GridProjetosIntegrados.DataBind();

        }

        protected void GridSolicitacoesSites_Sorting(object sender, GridViewSortEventArgs e)
        {
            string sortExpressionSolicitacoes = e.SortExpression;
            ViewState["sortExpressionSolicitacoes"] = sortExpressionSolicitacoes;

            if (GridViewSortDirectionSolicitacoes == SortDirection.Ascending)
            {
                GridViewSortDirectionSolicitacoes = SortDirection.Descending;
                SortGridView(sortExpressionSolicitacoes, DESCENDING, GridSolicitacoesSites);
            }
            else
            {
                GridViewSortDirectionSolicitacoes = SortDirection.Ascending;
                SortGridView(sortExpressionSolicitacoes, ASCENDING, GridSolicitacoesSites);
            }
        }

        protected void GridProjetosEmAndamento_Sorting(object sender, GridViewSortEventArgs e)
        {
            string sortExpressionAndamento = e.SortExpression;
            ViewState["sortExpressionAndamento"] = sortExpressionAndamento;

            if (GridViewSortDirectionAndamento == SortDirection.Ascending)
            {
                GridViewSortDirectionAndamento = SortDirection.Descending;
                SortGridView(sortExpressionAndamento, DESCENDING, GridProjetosEmAndamento);
            }
            else
            {
                GridViewSortDirectionAndamento = SortDirection.Ascending;
                SortGridView(sortExpressionAndamento, ASCENDING, GridProjetosEmAndamento);
            }
        }

        protected void GridProjetosIntegrados_Sorting(object sender, GridViewSortEventArgs e)
        {
            string sortExpressionIntegrados = e.SortExpression;
            ViewState["sortExpressionIntegrados"] = sortExpressionIntegrados;

            if (GridViewSortDirectionIntegrados == SortDirection.Ascending)
            {
                GridViewSortDirectionIntegrados = SortDirection.Descending;
                SortGridView(sortExpressionIntegrados, DESCENDING, GridProjetosIntegrados);
            }
            else
            {
                GridViewSortDirectionIntegrados = SortDirection.Ascending;
                SortGridView(sortExpressionIntegrados, ASCENDING, GridProjetosIntegrados);
            }
        }

        private void SortGridView(string sortExpression, string direction, GridView grid)
        {
            List<DemandModel> lst = null;

            switch (grid.ID)
            {
                case "GridSolicitacoesSites":
                    lst = (List<DemandModel>)Session["solicitacoes"];

                    GridProjetosEmAndamento.DataSource = (List<DemandModel>)Session["andamento"];
                    GridProjetosEmAndamento.DataBind();

                    GridProjetosIntegrados.DataSource = (List<DemandModel>)Session["entregue"];
                    GridProjetosIntegrados.DataBind();

                    break;
                case "GridProjetosEmAndamento":
                    lst = (List<DemandModel>)Session["andamento"];

                    GridSolicitacoesSites.DataSource = (List<DemandModel>)Session["solicitacoes"];
                    GridSolicitacoesSites.DataBind();

                    GridProjetosIntegrados.DataSource = (List<DemandModel>)Session["entregue"];
                    GridProjetosIntegrados.DataBind();

                    break;
                case "GridProjetosIntegrados":
                    lst = (List<DemandModel>)Session["entregue"];

                    GridSolicitacoesSites.DataSource = (List<DemandModel>)Session["solicitacoes"];
                    GridSolicitacoesSites.DataBind();

                    GridProjetosEmAndamento.DataSource = (List<DemandModel>)Session["andamento"];
                    GridProjetosEmAndamento.DataBind();

                    break;
            }

            switch (sortExpression)
            {
                case "Id":
                    {
                        if (direction == ASCENDING)
                            lst.Sort(delegate(DemandModel dem1, DemandModel dem2) { return dem1.ID.CompareTo(dem2.ID); });
                        else if (direction == DESCENDING)
                            lst.Sort(delegate(DemandModel dem1, DemandModel dem2) { return dem2.ID.CompareTo(dem1.ID); });
                    }
                    break;
                case "Title":
                    {
                        if (direction == ASCENDING)
                            lst.Sort(delegate(DemandModel dem1, DemandModel dem2) { return dem1.Title.CompareTo(dem2.Title); });
                        else if (direction == DESCENDING)
                            lst.Sort(delegate(DemandModel dem1, DemandModel dem2) { return dem2.Title.CompareTo(dem1.Title); });
                    }
                    break;
                case "State":
                    {
                        if (direction == ASCENDING)
                            lst.Sort(delegate(DemandModel dem1, DemandModel dem2) { return dem1.State.CompareTo(dem2.State); });
                        else if (direction == DESCENDING)
                            lst.Sort(delegate(DemandModel dem1, DemandModel dem2) { return dem2.State.CompareTo(dem1.State); });
                    }
                    break;
                case "StartDate":
                    {
                        if (direction == ASCENDING)
                            lst.Sort(delegate(DemandModel dem1, DemandModel dem2) { return dem1.Start.Value.CompareTo(dem2.Start.Value); });
                        else if (direction == DESCENDING)
                            lst.Sort(delegate(DemandModel dem1, DemandModel dem2) { return dem2.Start.Value.CompareTo(dem1.Start.Value); });
                    }
                    break;
                case "ConcludeDate":
                    {
                        if (direction == ASCENDING)
                            lst.Sort(delegate(DemandModel dem1, DemandModel dem2) { return dem1.Conclude.Value.CompareTo(dem2.Conclude.Value); });
                        else if (direction == DESCENDING)
                            lst.Sort(delegate(DemandModel dem1, DemandModel dem2) { return dem2.Conclude.Value.CompareTo(dem1.Conclude.Value); });
                    }
                    break;
                case "Hours":
                    {
                        if (direction == ASCENDING)
                            lst.Sort(delegate(DemandModel dem1, DemandModel dem2) { return dem1.UsedHours.CompareTo(dem2.UsedHours); });
                        else if (direction == DESCENDING)
                            lst.Sort(delegate(DemandModel dem1, DemandModel dem2) { return dem2.UsedHours.CompareTo(dem1.UsedHours); });
                    }
                    break;
                case "AssignedTo":
                    {
                        if (direction == ASCENDING)
                            lst.Sort(delegate(DemandModel dem1, DemandModel dem2) { return dem1.AssignedTo.CompareTo(dem2.AssignedTo); });
                        else if (direction == DESCENDING)
                            lst.Sort(delegate(DemandModel dem1, DemandModel dem2) { return dem2.AssignedTo.CompareTo(dem1.AssignedTo); });
                    }
                    break;
                case "Project":
                    {
                        if (direction == ASCENDING)
                            lst.Sort(delegate(DemandModel dem1, DemandModel dem2) { return dem1.Project.CompareTo(dem2.Project); });
                        else if (direction == DESCENDING)
                            lst.Sort(delegate(DemandModel dem1, DemandModel dem2) { return dem2.Project.CompareTo(dem1.Project); });
                    }
                    break;
            }
            grid.DataSource = lst;
            grid.DataBind();
        }

        #region IDiscriminatorDemand Members

        void IDiscriminatorDemand.ExibirFila(IEnumerable<CDSBDemandControl.Model.DemandModel> demandModels)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirEsteira(IEnumerable<CDSBDemandControl.Model.DemandModel> demandModels)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirRanking(IEnumerable<CDSBDemandControl.Model.DeveloperModel> developers, IEnumerable<CDSBDemandControl.Model.DeveloperModel> leaders, IEnumerable<CDSBDemandControl.Model.DeveloperModel> focalpoints)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirAtrasos(IEnumerable<CDSBDemandControl.Model.DemandModel> PendingDemands, IEnumerable<CDSBDemandControl.Model.DemandModel> Concludeddemands)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirFaturamento(List<CDSBDemandControl.Model.BillingModel> billing, bool canSeeBilling)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirCodeReview(IEnumerable<CDSBDemandControl.Model.DemandModel> WorkItemsWithCodeReview, IEnumerable<CDSBDemandControl.Model.DemandModel> WorkItemsWithoutCodeReview)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirBugsdeProducao(IEnumerable<CDSBDemandControl.Model.DemandModel> demandModels)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirListaDisp(IEnumerable<CDSBDemandControl.Model.DemandModel> list, IEnumerable<CDSBDemandControl.Model.DeveloperModel> modelAusencias, List<DateTime> fer)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirBugsdeProducaoUltimoMes(List<CDSBDemandControl.Model.DemandModel> BugList)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirFactoryWaitingList(List<CDSBDemandControl.Model.BillingModel> Billing, bool AllowsShow)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirAlocacao(IEnumerable<CDSBDemandControl.Model.DemandModel> demandModels)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirFactoryProductionList(List<CDSBDemandControl.Model.BillingModel> Billing, bool AllowsShow)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirManagementTeamTasks(List<CDSBDemandControl.Model.DemandModel> demandModels)
        {
            throw new NotImplementedException();
        }

        void IDiscriminatorDemand.ExibirScenariosAndTasks(List<CDSBDemandControl.Model.ScenarioModel> scenarios)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
